//
//  SLPermissionSetVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/25.
//

#import "SLPermissionSetVC.h"
#import "SLPermissionSetView.h"
@interface SLPermissionSetVC ()<CBPeripheralManagerDelegate>{
    CLAuthorizationStatus _locationStatus;
    NSString *_bluetoothStr;
}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)SLPermissionSetView *headView;
@property (strong, nonatomic) CBPeripheralManager *peripheralManager;
@end

@implementation SLPermissionSetVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpSubViews];
    [self checkLocationAuthorization];
    [self checkBluetoothAuthorization];
}

-(void)setUpSubViews{
    self.title = kLocalString(@"Permissions");
    [self.view addSubview:self.tableView];
    _headView = [SLPermissionSetView viewFromXIB];
    _headView.frame = self.tableView.bounds;
    kWeakSelf(self);
    [_headView setBtnBlock:^(NSInteger btnIndex) {
        [weakself handleSetView:btnIndex];
    }];
    _tableView.tableHeaderView = _headView;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateAuthStatus) name:@"backToApp" object:nil];
}

-(void)updateAuthStatus{
    [self checkLocationAuthorization];
    [self checkBluetoothAuthorization];
}

- (void)checkBluetoothAuthorization {
    if (!_peripheralManager) {
        _peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
    }
    
    // 检查蓝牙状态
    switch (_peripheralManager.state) {
        case CBManagerStatePoweredOn:
            _bluetoothStr = kLocalString(@"Allowed");
            NSLog(@"蓝牙已开启");
            // 这里可以执行使用蓝牙的操作
            break;
        case CBManagerStatePoweredOff:
            NSLog(@"蓝牙已关闭");
            _bluetoothStr = kLocalString(@"Close");
            // 处理蓝牙关闭的情况
            break;
        case CBManagerStateResetting:
            NSLog(@"蓝牙正在重置");
            // 处理重置状态
            break;
        case CBManagerStateUnauthorized:
            NSLog(@"蓝牙权限未授权");
            _bluetoothStr = kLocalString(@"Denied");
            // 处理权限未授权的情况
            break;
        case CBManagerStateUnsupported:
            NSLog(@"设备不支持蓝牙");
            _bluetoothStr = kLocalString(@"UnSupport");
            // 处理设备不支持蓝牙的情况
            break;
        case CBManagerStateUnknown:
            NSLog(@"蓝牙状态未知");
            _bluetoothStr = kLocalString(@"Unkown");
            // 处理状态未知的情况
            break;
        default:
            break;
    }
    _headView.perContentLbl2.text = _bluetoothStr;
}

-(void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
    [self checkBluetoothAuthorization]; // 每次状态更新时检查权限
}

-(void)checkLocationAuthorization {
    _locationStatus = [CLLocationManager authorizationStatus];
    BOOL isLocationAllow = _locationStatus == kCLAuthorizationStatusAuthorizedAlways || _locationStatus == kCLAuthorizationStatusAuthorizedWhenInUse;
    _headView.perContent1.text = isLocationAllow ? kLocalString(@"Allowed"):kLocalString(@"Denied");
    switch (_locationStatus) {
        case kCLAuthorizationStatusNotDetermined:
            NSLog(@"定位权限尚未决定");
            break;
        case kCLAuthorizationStatusRestricted:
            NSLog(@"定位权限受限");
            break;

        case kCLAuthorizationStatusDenied:
            NSLog(@"定位权限已拒绝");
            // 处理权限拒绝的情况
            break;

        case kCLAuthorizationStatusAuthorizedAlways:
            NSLog(@"定位权限已授权（始终）");
            // 这里可以执行有定位权限的操作
            break;

        case kCLAuthorizationStatusAuthorizedWhenInUse:
            NSLog(@"定位权限已授权（使用时）");
            // 这里可以执行有定位权限的操作
            break;

        default:
            break;
    }
}

-(void)requestLocationAuthorization {
    CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    [locationManager requestAlwaysAuthorization]; // 或者 requestAlwaysAuthorization
}

-(void)handleSetView:(NSInteger)index{
    if (index == 1) {
        if (_locationStatus == kCLAuthorizationStatusNotDetermined) {
            [self requestLocationAuthorization];
        }else{
            [self openSystemSetting];
        }
        
    }else if (index == 2){
        [self openSystemSetting];
    }
}

-(void)openSystemSetting{
    if (@available(iOS 10.0, *)) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
    }
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight,kScreenWidth,kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = KClearColor;
    }
    return _tableView;
}


@end
